package com.akk.platform;

import com.akk.common.enums.AdminEnums;
import com.akk.common.enums.AdminRoleEnums;
import com.akk.module.admin.entity.Admin;
import com.akk.module.admin.entity.AdminMenu;
import com.akk.module.admin.model.request.AdminForgotPwdReq;
import com.akk.module.admin.model.request.AdminLoginReq;
import com.akk.module.admin.service.AdminMenuService;
import com.akk.module.admin.service.AdminService;
import com.akk.module.user.entity.UserAgent;
import com.akk.module.user.service.UserAgentService;
import com.akk.utils.Constants;
import com.akk.utils.R;
import com.akk.utils.RestResponse;
import com.akk.utils.ShiroUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/platform")
public class AdminLoginAction {

    @Autowired
    AdminService adminService;
    @Autowired
    AdminMenuService adminMenuService;
    @Autowired
    UserAgentService userAgentService;

    @ResponseBody
    @RequestMapping(value = "/adminLogin", method = RequestMethod.POST)
    public RestResponse toLogin(@RequestBody AdminLoginReq adminLoginReq)throws IOException {
        try{
            Subject subject = ShiroUtils.getSubject();
            //sha256加密
            String password = new Sha256Hash(adminLoginReq.getPassword()).toHex();
            if(adminLoginReq.getAdminType().equals(AdminEnums.TypeEnum.MANAGE.getValue().toString())
                    ||adminLoginReq.getAdminType().equals(AdminEnums.TypeEnum.OEM.getValue().toString())){
                List<Admin> admins = adminService.findByAccount(adminLoginReq.getAccount());
                if(admins.isEmpty())
                    return RestResponse.build("2001","账号或密码不正确",null);
                UsernamePasswordToken token = new UsernamePasswordToken(adminLoginReq.getAccount(),password);
                subject.login(token);
                return RestResponse.build(admins.get(0));
            }else{
                List<UserAgent> agents = userAgentService.findByPhone(adminLoginReq.getAccount());
                if(agents.isEmpty() || !agents.get(0).getPassword().equals(password))
                    return RestResponse.build("2001","账号或密码不正确",null);
                return RestResponse.build(agents.get(0));
            }

        }catch (UnknownAccountException e) {
            return RestResponse.build("2001","用户信息未找到",null);
        }catch (IncorrectCredentialsException e) {
            return RestResponse.build("2001","账号或密码不正确",null);
        }catch (LockedAccountException e) {
            return RestResponse.build("2001","用户账号被锁定",null);
        }catch (AuthenticationException e) {
            return RestResponse.build("2001","账号验证失败",null);
        }catch (Exception e) {
            return RestResponse.build("2001","系统繁忙，请稍后再试",null);
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }


    @RequestMapping(value = "/forgotPwd",method = RequestMethod.POST)
    @ResponseBody
    public R forgotPwd(@RequestBody AdminForgotPwdReq adminForgotPwdReq){
        if(!adminForgotPwdReq.getCode()
                .equals(ShiroUtils.getSessionAttribute(Constants.FORGOT_PWD_SESSION_KEY))){
            return R.error("验证码错误");
        }
        List<Admin> admins = adminService.findByAccount(adminForgotPwdReq.getAccount());
        admins.get(0).setUpdateDate(new Date());
        admins.get(0).setPassword(new Sha256Hash(adminForgotPwdReq.getNewPwd()).toHex());
        adminService.save(admins.get(0));
        return  R.ok("密码修改成功");
    }

    @RequestMapping(value = "/adminmenu")
    @ResponseBody
    public RestResponse adminMenu() {
        Admin admin  = ShiroUtils.getAdmin();
        List<AdminMenu> menus = adminMenuService.findMenuByRoleId(admin.getRoleId());
        //组装菜单
        List<AdminMenu> menuTree = adminMenuService.getMenuTree(menus);
        //用户权限
        Set<String> permissions = adminMenuService.getAdminPermissions(menus);
        JSONObject json = new JSONObject();
        json.put("menuTree",menuTree);
        json.put("permissions",permissions);
        return RestResponse.build(json);
    }

    @RequestMapping(value = "/admininfo",method = RequestMethod.GET)
    @ResponseBody
    public RestResponse adminInfo(){
        return RestResponse.build(ShiroUtils.getAdmin());
    }
}
